<template>
  <div ref="chart" style="width: 100%; height: 260px"></div>
</template>
<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Chart",
});
</script>
<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from "vue";

import * as echarts from "echarts";
import "echarts-gl";
import { merge } from "lodash";
import china from "@/utils/china.json";
const chart = ref();
const props = defineProps(["option"]);
echarts.registerMap("china", china as any);
const option = {
  legend: {
    right: "2%",
    top: "10%",
    orient: "vertical",
    padding: 5,
    itemGap: 50,
    textStyle: {
      color: "white", // 设置图例文本颜色
      fontSize: 14, // 设置图例文本字体大小
    },
  },
  tooltip: {
    trigger: "item", // 触发类型，'item' 表示数据项图形触发，'axis' 表示坐标轴触发
    formatter: "{b}: {c}人 ({d}%)", // 提示框的内容格式，{a}（系列名），{b}（数据项名），{c}（数值），{d}（百分比），
    backgroundColor: "#071f4e", // 设置背景框颜色
    textStyle: {
      color: "#fff", // 设置字体颜色
    },
    borderColor: "#071f4e",
    position: function (
      point: number[],
      params: any,
      dom: HTMLElement,
      rect: DOMRect,
      size: number[]
    ) {
      // 鼠标位置 + 偏移量
      return {
        left: point[0] - 70, // 水平方向偏移量
        top: point[1] + 30, // 垂直方向偏移量
      };
    },
  },
};
//重置图表操作
let myChart: echarts.ECharts;
let timerId: number;
function resizeHandler() {
  myChart.resize(); // 重置图表大小
}

type TimeoutHandler = () => void;
const myTimeout = (handler: TimeoutHandler, timeout: number): number => {
  return setTimeout(handler, timeout) as unknown as number;
};
onMounted(() => {
  myChart = echarts.init(chart.value);
  myChart.setOption(merge(option, props.option));
  timerId = myTimeout(() => {
    resizeHandler();
  }, 10);
  window.addEventListener("resize", resizeHandler);
});
onUnmounted(() => {
  clearTimeout(timerId);
  if (myChart) {
    myChart.dispose();
  }
  window.removeEventListener("resize", resizeHandler);
});
</script>

<style lang="scss" scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style>
